<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->

    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
      <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="param.orderType"
              style="width: 150px;margin-right:15px;"
              placeholder="请输入工别"
        ></el-input>

        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="param.workOrderNo"
              style="width: 150px;margin-right:15px;"
              placeholder="请输入工单"
        ></el-input>

        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="param.sectionNo"
              style="width: 150px;margin-right:15px;"
              placeholder="请输入工段"
        ></el-input>

        <el-date-picker
            placeholder="开工时间"
            v-model="dateOptions"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            style="margin-right:15px;">
        </el-date-picker>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="工单号"  prop="work_order_no" align="center">
        <template slot-scope="scope" >
          {{scope.row.order_type + '-'+ scope.row.work_order_no}}
        </template>
      </el-table-column>
      <el-table-column label="任务令"  prop="po" align="center"/>
      <el-table-column label="工单品号"  prop="produce_no" align="center"/>
      <el-table-column label="客户编码"  prop="client_number" align="center"/>
      <el-table-column label="生产工段"  prop="section_no" align="center"/>
      <el-table-column label="线体名称"  prop="section_name" align="center" width="200"/>
      <el-table-column label="负责人"  prop="user_name" align="center"/>
      <el-table-column label="工单台数"  prop="plan_number" align="center"/>
      <el-table-column label="装配工序总数"  prop="process_order_sum" align="center"/>
      <el-table-column label="起始工序台数"  prop="all_count_asc" align="center"/>
      <el-table-column label="结束工序台数"  prop="all_count_desc" align="center"/>
      <el-table-column label="QC检验台数"  prop="QC_count" align="center"/>
      <el-table-column label="QC检验问题数"  prop="QC_disqualification_count" align="center"/>
      <el-table-column label="OQC检验台数"  prop="OQC_count" align="center"/>
      <el-table-column label="OQC检验问题数"  prop="OQC_disqualification_count" align="center"/>
      <el-table-column label="上线时间"  prop="online_time" align="center" width="150"/>
      <el-table-column label="生产周期" align="center" width="130">
        <template slot-scope="scope" >
            {{ dataTime(scope.row.online_time) }}
        </template>
      </el-table-column>
    </el-table>

   <!-- pagination 分页 -->
    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div> -->

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { findOnLineWorkOrder } from "@/api/staffscan"
import { getCenter } from '../../api/workSection.js'
export default {
    name: 'emsInformation',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                code: '',                      
                content: ''                    
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            tableMX:[],
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            props: { multiple: true },
            dateOptions: this.getNowTime(),
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            // 表单校验
            addRules: {
                code: [
                    { required: true, message: "条码不能为空!", trigger: "change" },
                ],
                content: [
                    { required: true, message: "点检内容不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            barcodeType1List: [],
            accessTypeList: ['出库','入库'],
            barcodeType3List: []
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        getNowTime() {
                let dateTime = +new Date()+8*3600*1000
                const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
                    .toISOString()
                    .replace('T', ' ')
                    .split('.')[0] //默认开始时间7天前
                const end = new Date(dateTime)
                    .toISOString()
                    .replace('T', ' ')
                    .split('.')[0]//默认结束时间当前时间
                console.log([start, end])
                return [start, end]
            },
        // 计算相差天数
        dataTime(time){
                var dataTime = new Date(time);
                // 获取当前时间
                var currentTime = new Date();
                // 计算时间差，单位为毫秒
                var timeDiff = currentTime - dataTime;
                // 将时间差转换为秒数
                var totalSecondsDiff = Math.floor(timeDiff / 1000);
                // 计算天数
                var days = Math.floor(totalSecondsDiff / (24 * 3600));
                totalSecondsDiff %= (24 * 3600);
                // 计算小时数
                var hours = Math.floor(totalSecondsDiff / 3600);
                totalSecondsDiff %= 3600;
                // 计算分钟数
                var minutes = Math.floor(totalSecondsDiff / 60);
                return days+ "天"+ hours+ "小时"+ minutes+ "分钟"
            },
        getData(){
        //   this.listQuery.page = 1
        //   this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = {}
            if(this.dateOptions){ query.startTime = this.dateOptions[0],query.endTime = this.dateOptions[1]}
            if(this.param.orderType){ query.orderType = this.param.orderType}
            if(this.param.workOrderNo){ query.workOrderNo = this.param.workOrderNo}
            if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
            query.type = 2
            let data = await findOnLineWorkOrder(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.tableInfo = data.data
        },
        // table表单下方的页码组件改变每页显示的数据条数
        // handleSizeChange(val) {
        //   this.listQuery.limit = val
        //   this.handleFilter()
        // },
        // table表单下方的页码组件改变页面
        // handleCurrentChange(val) {
        //   this.listQuery.page = val
        //   this.handleFilter()
        // },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            work_order_no: '工单号',
            po: '任务令',
            produce_no: '工单品号',
            client_number: '客户编码',
            section_no: '生产工段',
            section_name: '线体名称',
            user_name: '负责人',
            plan_number: '工单台数',
            process_order_sum: '装配工序总数',
            all_count_asc: '起始工序台数',
            all_count_desc: '结束工序台数',
            QC_count: 'QC检验台数',
            QC_disqualification_count: 'QC检验问题数',
            OQC_count: 'OQC检验台数',
            OQC_disqualification_count: 'OQC检验问题数',
            online_time: '上线时间',
            JGTime: '生产周期',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = {}
          query.type = 2
          if(this.dateOptions){ query.startTime = this.dateOptions[0],query.endTime = this.dateOptions[1]}
          if(this.param.orderType){ query.orderType = this.param.orderType}
          if(this.param.workOrderNo){ query.workOrderNo = this.param.workOrderNo}
          if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
          let arr = await findOnLineWorkOrder(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: 'EMS车间信息化看板', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              work_order_no: item.order_type + '-' + item.work_order_no,
              po: item.po,
              produce_no: item.produce_no,
              client_number: item.client_number,
              section_no: item.section_no,
              section_name: item.section_name,
              user_name: item.user_name,
              plan_number: item.plan_number,
              process_order_sum: item.process_order_sum,
              all_count_asc: item.all_count_asc,
              all_count_desc: item.all_count_desc,
              QC_count: item.QC_count,
              QC_disqualification_count: item.QC_disqualification_count,
              OQC_count: item.OQC_count,
              OQC_disqualification_count: item.OQC_disqualification_count,
              online_time: item.online_time,
              JGTime: this.dataTime(item.online_time),
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {   
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
